class UsersController < ApplicationController
  # before_action用于在访问controller接口之前执行一个函数，这里是执行authorized判断用户是否登录
  # only参数是一个数组，指定哪些接口需要执行这个函数
  before_action :authorized, only: %i[auto_login update edit destroy logout reset_pwd]
  include UserResponse
  # 注册
  def create
    @user = User.create(user_params)
    if @user.valid? # 字段验证，如长度，unique之类的
      token = encode_token({ user_id: @user.id }) # 使用用户的id来生成token，这里还可以加入email之类的字段
      render json: { error_code: 10, user: @user, token: token }
    else
      render json: { error_code: 11, message: @user.errors.messages }
    end
  end

  # 登录
  def login
    @user = User.find_by(username: params[:username])
    if @user&.authenticate(params[:password])
      # 使用&符号可以自动判断@user是否为nil，就不用写成 if @user && @user.authenticate
      # authenticate是bcrypt插件提供给model的函数，用于验证密码哈希
      token = encode_token({ user_id: @user.id }) # 使用用户的id来生成token，这里还可以加入email之类的字段
      render json: { user: @user, token: token }
    else
      render json: json_err_msg(error_code: 13, message: 'Invalid username or password')
    end
  end

  # 登出
  def logout
    logged_in_user
    token = encode_token({ user_id: nil })
    render json: { error: 10, message: "You've logged out!", token: token }
  end

  # 自动登录
  def auto_login
    # 这里也可以是其他的功能，比如返回活动列表
    render json: @user
  end

  # 注销用户
  def destroy
    @user.destroy
    render json: { error_code: 10, message: 'ok' }
  end

  # 编辑或查看用户信息
  def view
    @user = User.find_by(username: params[:username])
    if @user
      render json: {
        user: UserRepresenter.new(@user).json_user_info
      }
    else
      render json: { error_code: 1, message: 'User doesn\'t exist.' }
    end
  end

  # 根据id查找用户
  def view_id
    @user = User.find_by(id: params[:id])
    if @user
      render json: {
        user: @user
      }
    else
      render json: { error_code: 1, message: 'User doesn\'t exist.' }
    end
  end

  # 更新用户信息
  def update
    logged_in_user
    user_update_params.each do |key, value|
      @user.update_attribute(key, value)
    end
    render json: { user: UserRepresenter.new(@user).json_user_info,
                   error_code: 10,
                   message: 'Update successfully information. ' }
  end

  # 重设密码
  def reset_pwd
    logged_in_user
    if @user&.authenticate(params[:old_pwd])
      if params[:new_pwd] == params[:new_pwd_confirmation]
        @user.update(password: params[:new_pwd])
        token = encode_token({ user_id: nil })
        render json: {
          message: '更改密码成功，请重新登录！',
          token: token
        }
      else
        render json: json_err_msg(error_code: 16, message: '两次密码不一致！')
      end
    else
      render json: json_err_msg(error_code: 15, message: '原密码不正确!')
    end
  end

  private

  # 参数限制
  def user_params
    params.permit(:username, :password, :email, :full_name,
                  :school, :major, :avatar,
                  :cnt_finished, :cnt_break, :credit,
                  :gender, :favourite, :desc) # 只允许用户名、密码、年龄，其他参数将忽略
  end

  # 更新用户信息的参数限制
  def user_update_params
    params.permit(:email, :full_name,
                  :school, :major, :avatar,
                  :gender, :favourite, :desc)
  end

  # 更新密码时用到的参数限制
  def reset_pwd_params
    params.permit(:old_pwd, :new_pwd, :new_pwd_confirmation)
  end
end
